import com.demo.model.User;
import com.fasterxml.jackson.core.*;
import org.junit.Test;

import java.io.File;
import java.io.IOException;

/**
 * @Auther: luobiao
 * @Date: 2020/6/13 20:28
 * @Description: 第二章示例
 */
public class C02 {
    /**
     * 生成json对象写入到文件中
     * @throws IOException
     */
    @Test
    public void test1() throws IOException {
        File file = new File("user.json");
        JsonFactory factory = new JsonFactory();
        JsonGenerator generator = factory.createGenerator(file, JsonEncoding.UTF8);
        generator.writeStartObject();
        generator.writeStringField("name", "luobiao");
        generator.writeNumberField("age", 18);
        generator.writeEndObject();
        generator.close();
    }

    /**
     * 从文件中读取json对象输出
     * @throws IOException
     */
    @Test
    public void test2() throws IOException {
        File file = new File("user.json");
        JsonFactory factory = new JsonFactory();
        JsonParser parser = factory.createParser(file);
        JsonToken token = null;
        while ((token = parser.nextToken()) != JsonToken.END_OBJECT) {
            if ("name".equals(parser.currentName())) {
                String name = parser.getValueAsString();
                System.out.println("toke="+token+";name="+name);
            }
            if ("age".equals(parser.currentName())) {
                int age = parser.getValueAsInt();
                System.out.println("toke="+token+";age="+age);
            }

        }
        parser.close();
    }

    /**
     * 从文件中读取json对象输出
     * @throws IOException
     */
    @Test
    public void test3() throws IOException {
        File file = new File("user.json");
        JsonFactory factory = new JsonFactory();
        JsonParser parser = factory.createParser(file);
        User user=parser.readValueAs(User.class);
        System.out.println(user);
        parser.close();
    }


}
